package com.youseu.taoliving.commodity.service.impl;

import com.baomidou.mybatisplus.core.toolkit.support.BiIntFunction;
import com.youseu.taoliving.commodity.vo.Catalog2Vo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youseu.common.utils.PageUtils;
import com.youseu.common.utils.Query;

import com.youseu.taoliving.commodity.dao.CategoryDao;
import com.youseu.taoliving.commodity.entity.CategoryEntity;
import com.youseu.taoliving.commodity.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //按照层级排列
        return entities.stream().filter(categoryEntity ->
                categoryEntity.getParentId() == 0 //取出一级分类
        ).map(categoryEntity -> {//递归设置子类
            categoryEntity.setChildrenCategories(getChildrenCategories(categoryEntity, entities));
            return categoryEntity;
        }).sorted((categoryEntity1, categoryEntity2) -> {
            return categoryEntity1.getSort() - categoryEntity2.getSort();
        }).collect(Collectors.toList());
    }


    private List<CategoryEntity> getChildrenCategories(CategoryEntity root, List<CategoryEntity> entities) {
        return entities.stream().filter(categoryEntity ->
                Objects.equals(categoryEntity.getParentId(), root.getId())
        ).map(categoryEntity -> {
            categoryEntity.setChildrenCategories(getChildrenCategories(categoryEntity, entities));
            return categoryEntity;
        }).sorted((categoryEntity1, categoryEntity2) -> {
            return categoryEntity1.getSort() - categoryEntity2.getSort();
        }).collect(Collectors.toList());
    }

    @Override
    public Long[] getCascadedCategoryId(Long categoryId) {
        List<Long> list = new ArrayList<>();
        //将id依次传入list
        getParentCategoryId(list, categoryId);
        //翻转数组 将父类id放前面
        Collections.reverse(list);
        return list.toArray(new Long[0]);
    }

    @Override
    public List<CategoryEntity> getFirstLevelCategories() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        //返回一级分类
        wrapper.eq("cat_level", 1);
        return this.baseMapper.selectList(wrapper);
    }


    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //查询分类所有信息
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);
        List<CategoryEntity> level1Categories = getParent_cid(categoryEntities, 0L);

        //根据前端要求json格式返回数据
        return level1Categories.stream().collect(Collectors.toMap(k -> {
            //取出1级分类id
            return k.getId().toString();
        }, v -> {
            //得到2级分类
            List<CategoryEntity> level2Categories = getParent_cid(categoryEntities, v.getId());
            return level2Categories.stream().map(level2item -> {
                Catalog2Vo catalog2Vo = new Catalog2Vo(v.getId().toString(), null,level2item.getId().toString(), level2item.getName());
                //得到三级分类
                List<CategoryEntity> level3Categories = getParent_cid(categoryEntities, level2item.getId());
                //遍历设置内部类catalog3Vo
                List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Categories.stream().map(level3item -> {
                    return new Catalog2Vo.Catalog3Vo(level2item.getId().toString(), level3item.getId().toString(), level3item.getName());
                }).collect(Collectors.toList());
                //catalog3Vos作为属性设置到catalog2Vo
                catalog2Vo.setCatalog3List(catalog3Vos);
                return catalog2Vo;
            }).collect(Collectors.toList());
        }));
    }

    /**
     * 辅助方法 用于getCatalogJson
     * @param categoryEntities 所有分类信息
     * @param parent_cid       父分类id
     * @return
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntities,
                                               Long parent_cid) {
        //过滤得到父id下的子类
        return categoryEntities.stream()
                .filter(item -> item.getParentId().equals(parent_cid))
                .collect(Collectors.toList());
    }

    private List<Long> getParentCategoryId(List<Long> list, Long categoryId) {
        list.add(categoryId);
        CategoryEntity entity = this.getById(categoryId);
        if (entity.getParentId() != 0) {//将父类id放进list
            //递归添加 知道到顶层(父类id=0)
            getParentCategoryId(list, entity.getParentId());
        }
        return list;
    }

}